<template>
  <avue-crud
    :data="data"
    :option="option"
    :page.sync="page"
    @on-load="fetch"
    @row-save="rowSave"
    @row-update="rowUpdate"
    @row-del="rowDel"
    @size-change="sizeChange"
    @current-change="currentChange"
    @sort-change="sortChange"
    @search-change="searchChange"
  ></avue-crud>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
@Component({})
export default class ResourceCrud extends Vue {
  @Prop({ type: String }) resource?: string

  data = []
  option = {}
  page = {
    total: 0,
    currentPage: 1,
    pageSize: 2,
    pageSizes: [2, 5, 10]
  }

  query: any = {
    limit: 2
  }

  async fetchOption () {
    const result = await this.$http.get(`${this.resource}/option`)

    this.option = result.data
  }

  // size改变了
  sizeChange (val) {
    this.page.currentPage = 1
    this.page.pageSize = val

    this.query.page = 1
    this.query.limit = val
    this.fetch()
  }

  // 页码改变了
  currentChange (val) {
    this.page.currentPage = val
    this.query.page = val

    this.fetch()
  }

  // 排序
  async sortChange ({ prop, order }) {
    if (!order) {
      this.query.sort = null
    } else {
      this.query.sort = {
        [prop]: order === 'ascending' ? 1 : -1
      }
    }

    this.fetch()
  }

  // 搜索
  searchChange (params, done) {
    for (const k in params) {
      const field = this.option.column.find(v => v.prop === k)

      if (field.regex) {
        params[k] = { $regex: params[k] }
      }
    }

    this.query.where = params
    this.query.page = 1
    this.fetch()
    done()
  }

  async fetch () {
    const result = await this.$http.get(`${this.resource}`, {
      params: {
        query: this.query
      }
    })

    this.data = result.data.data
    this.page.total = result.data.total
  }

  created () {
    // this.fetch()
    this.fetchOption()
  }

  // 新增
  async rowSave (row, done) {
    await this.$http.post(`${this.resource}`, row)
    this.$message.success('新增成功')
    this.fetch()
    done()
  }

  // 修改
  async rowUpdate (row, index, done) {
    const data = JSON.parse(JSON.stringify(row))
    delete data.$index
    await this.$http.put(`${this.resource}/${row._id}`, data)
    this.$message.success('修改成功')
    this.fetch()
    done()
  }

  // 删除
  async rowDel (row, index) {
    try {
      await this.$confirm('确定删除吗？')
    } catch (error) {
      return
    }

    await this.$http.delete(`${this.resource}/${row._id}`)
    this.$message.success('删除成功')
    this.fetch()
  }
}
</script>
